package at.fhooe.mcm.logic.logging;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import at.fhooe.mcm.logic.core.Core;

public class XMLLoggingService extends LoggingService
{
	File						m_file;
	BufferedWriter				m_out;

	public static final String	NAME			= "logging.xml";
	public static final String	LOGGING_SROUCE	= "XMLLoggingService";

	public static XMLLoggingService getInstance(Core _core)
	{
		return (XMLLoggingService) _core.getService(NAME);
	}

	public XMLLoggingService(int _level)
	{
		m_level = _level;
	}

	public XMLLoggingService()
	{
		this(WARNING);
	}

	@Override
	public String getName()
	{
		return NAME;
	}
	
	public void logSensorData(String _id, String _type, String _name, String _value)
	{
		try
		{
			m_out.write("\t<record>\n");
			m_out.write("\t\t<date>" + timeToString(m_core.getTime()) + "</date>\n");
			m_out.write("\t\t<id>" + _id + "</id>\n");
			m_out.write("\t\t<type>" + _type + "</type>\n");
			m_out.write("\t\t<name>" + _name + "</name>\n");
			m_out.write("\t\t<value>" + _value + "</value>\n");
			m_out.write("\t</record>\n");
			m_out.flush();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void log(int _level, String _source, String _message)
	{
		
	}

	@Override
	public void initialize(Core _core)
	{
		m_core = _core;
		
		try
		{
			DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); 
			
			String filename = "log_" + dateFormat.format(m_core.getTime()) + ".xml";
			File f = new File(filename);
			
			if (!f.exists())
			{
				f.createNewFile();
			}

			m_out = new BufferedWriter(new FileWriter(f));
			initializeXML();

		}
		catch (IOException _ioe)
		{
			ConsoleLoggingService.getInstance(m_core).logWarning(LOGGING_SROUCE, _ioe.getMessage());
		}
	}

	@Override
	public void shutdown(Core core)
	{

		try
		{
			closeXML();
			m_out.close();
		}
		catch (IOException _ioe)
		{
			ConsoleLoggingService.getInstance(m_core).logWarning(LOGGING_SROUCE, _ioe.getMessage());
		}

	}

	private void initializeXML() throws IOException
	{

		m_out.write("<?xml version=\"1.0\" encoding=\"windows-1252\"standalone=\"no\"?>\n");
		m_out.write("<!DOCTYPE log SYSTEM \"logger.dtd\">\n\n");
		m_out.write("<log>\n");
		m_out.flush();

	}

	private void closeXML()
	{
		try
		{
			m_out.write("</log>\n");
			m_out.flush();
		}
		catch (IOException _ioe)
		{
			ConsoleLoggingService.getInstance(m_core).logWarning(LOGGING_SROUCE, _ioe.getMessage());
		}
	}
}
